<template>
  <div class="base-container">
    <t-form ref="form" :data="queryParams" label-width="80" @submit="()=>{this.queryParams.pageNum=1;this.pagination.current=1;this.getList()}"
            @reset="()=>{this.queryParams.pageNum=1;this.pagination.current=1;this.getList()}">
      <t-row style="border-bottom: 1px solid #E5E6EB;margin-bottom: 10px">
        <t-col :span="11" class="query-form-inline">
          <t-form-item label="项目名称" name="projectName">
            <t-input
              v-model="queryParams.projectName"
              clearable
              placeholder="请输入项目名称"
              style="width: 240px"
            />
          </t-form-item>
          <t-form-item label="变更类型" name="subjectClassification">
            <t-select style="width: 240px" clearable v-model="queryParams.changeType"
                      :options="dict.type.change_type">
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button theme="primary" type="submit">查询</t-button>
          <t-button theme="default" variant="outline" type="reset">重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <div class="btn-group-inline">
      <t-button @click="toApply" variant="outline" theme="primary">
        <t-icon name="add" slot="icon"/>
        新增变更申请
      </t-button>
      <span style="color: red">注意:目前所有变更申请都需要先走线下，盖好章，然后再到系统补录变更后的数据。</span>
    </div>
    <t-table
      rowKey="id"
      :data="data"
      :columns="site_tag === 'jtt'?columns:columns.filter(val=>{ return  val.title!=='计划类别'})"
      hover
      :pagination="pagination"
      :loading="dataLoading"
      :selected-row-keys="selectedRowKeys"
      :sort="sort"
      :hideSortTips="true"
      @sort-change="sortChange"
    >
      <template #[`contract.projectName`]="{ row }">
        <t-link v-if="row.project.version === '2024'" @click="dialog.objId=row.projectId;dialog.header=row.contract.projectName;dialog.open_item_detail=true" hover="color"
                theme="primary">{{ row.contract.projectName }}
        </t-link>
        <t-link v-else @click="dialog.objId=row.projectId;dialog.header=row.contract.projectName;dialog.open_project_detail=true" hover="color"
                theme="primary">{{ row.contract.projectName }}
        </t-link>
      </template>
      <template #[`contract.adviceFunding`]="{row}">
        {{row.contract.adviceFunding}}万元
      </template>
      <template #[`contract.subsidyFunding`]="{row}">
        {{row.contract.subsidyFunding}}万元
      </template>
      <template #changeType="{row}">
        {{ row.changeType | filterByDict(dict.type.change_type) }}
      </template>
      <template #[`project.subjectClassification`]="{ row }">
        {{ row.project.subjectClassification | filterByDict(dict.type.subject_classification) }}
      </template>
      <template #[`project.projectType`]="{ row }">
        {{ row.project.projectType | filterByDict(dict.type.project_type) }}
      </template>
      <template #[`project.projectCategory`]="{ row }">
        {{ row.project.projectCategory | filterParentsByTree(projectCategoryOptions,children = "children", id = "id", label = "name") }}
      </template>
      <template #[`project.projectStatus`]="{ row }">
        <t-tag @click="dialog.header=row.projectName;dialog.objId=row.projectId;dialog.open_approve_list=true" class="cursor-pointer"  :theme="handleTheme(row.project.projectStatus, dict.type.project_status)" variant="light">
          {{ row.project.projectStatus | filterByDict(dict.type.project_status) }}
        </t-tag>
      </template>
      <template #status="{ row }">
        <t-tag @click="dialog.header=row.contract.projectName;dialog.objId=row.projectId;dialog.open_approve_list=true" class="cursor-pointer" v-if="row.status" :theme="handleTheme(row.status,dict.type.approve_status)" variant="light">
          {{ row.status | filterByDict(dict.type.approve_status) }}
        </t-tag>
        <t-tag @click="dialog.header=row.contract.projectName;dialog.objId=row.projectId;dialog.open_approve_list=true" class="cursor-pointer" v-else theme="warning" variant="light">未提交</t-tag>
      </template>
      <template #op="{ row }">
        <t-button v-if="['1','4',null].includes(row.status)" @click="update(row,1)" size="small"
                  variant="text" class="t-button-link">
          <t-icon name="edit-1" slot="icon"/>
          继续变更
        </t-button>
        <t-button size="small" @click="dialog.header=row.contract.projectName;dialog.objId=row.id;dialog.open_detail=true" variant="text" class="t-button-link">
          <t-icon name="info-circle" slot="icon"/>
          详情
        </t-button>
        <t-button @click="createPDF(row)" size="small"
                  variant="text" class="t-button-link">
          <t-icon name="file-pdf" slot="icon"/>
          导出PDF
        </t-button>
        <t-button  v-if="['1','4', null].includes(row.status)" theme="danger" @click="delObj(row)" size="small" variant="text" class="t-button-link">
          <t-icon name="delete" slot="icon"/>
          删除
        </t-button>
      </template>
    </t-table>
    <project-detail-dialog tab-default-value="3" :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_project_detail"
                           v-if="dialog.open_project_detail"></project-detail-dialog>
    <item-detail-dialog tab-default-value="2" :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_item_detail"
                           v-if="dialog.open_item_detail"></item-detail-dialog>
    <approve-list :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_approve_list" v-if="dialog.open_approve_list"></approve-list>
    <change-apply-detail-dialog :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_detail" v-if="dialog.open_detail"></change-apply-detail-dialog>

  </div>
</template>

<script>
import projectDetailDialog from "../pm/components/project-detail-dialog.vue";
import ItemDetailDialog from "../pm/components/item-detail-dialog.vue";
import ApproveList from "../approve/components/approve-list.vue";
import ChangeApplyDetailDialog from "./components/change-apply-detail-dialog.vue";


export default {
  name: "change-apply",
  dicts: ['change_type', 'approve_status', 'project_status', 'subject_classification', 'project_type'],
  components:{
    projectDetailDialog,
    ApproveList,
    ChangeApplyDetailDialog,
    ItemDetailDialog
  },
  data(){
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      selectedRowKeys: [],
      sort: [],
      dialog: {
        open_project_detail: false,
        open_approve_list: false,
        header: "",
        objId: null,
        open: false,
        open_detail: false,
        open_item_detail: false,
      },
      data: [],
      columns: [
        {
          colKey: "project.projectNum",
          title: "项目编号",
          align: "center",
          width: 120,
          // sorter: true,
          // ellipsis: true,
        },
        {
          colKey: "contract.projectName",
          title: "项目名称",
          align: "center",
          width: 220
        },
        {
          colKey: "changeType",
          title: "变更类型",
          align: "center",
          width: 100
        },
        {
          colKey: "contract.adviceFunding",
          title: "建议经费总概算",
          align: "center",
          width: 160,
          sorter: true,
        },
        {
          colKey: "contract.subsidyFunding",
          title: import.meta.env.VITE_SITE_TAG==='jtt'?"厅拨经费":`集团补助经费`,
          align: "center",
          sorter: true,
          width: 140,
        },
        {
          colKey: "contract.startDate",
          title: "任务书开始时间",
          align: "center",
          sorter: true,
          width: 160,
        },
        {
          colKey: "contract.completeDate",
          title: "任务书结束时间",
          align: "center",
          sorter: true,
          width: 160,
        },
        {
          colKey: "project.projectLeaderName",
          title: "项目负责人",
          align: "center",
          width: 120
        },
        {
          colKey: "nickName",
          title: "填报人",
          align: "center",
          width: 100
        },
        {
          colKey: "project.declareDeptName",
          title: "承担单位",
          align: "center",
          width: 180,
          sorter: true
        },
        {
          colKey: "project.projectCategory",
          title: "计划类别",
          align: "center",
          width: 120
        },
        {
          colKey: "project.subjectClassification",
          title: "学科分类",
          align: "center",
          width: 100
        },
        {
          colKey: "project.projectType",
          title: "项目类型",
          align: "center",
          width: 120
        },
        // {
        //   colKey: "createTime",
        //   title: "创建时间",
        //   align: "center",
        // },
        {
          colKey: "project.projectStatus",
          title: "项目状态",
          align: "center",
          width:220,
          fixed: 'right',
          sorter: true
        },
        {
          colKey: "status",
          title: "审批状态",
          align: "center",
          width: 120,
          fixed: 'right'
        },
        {
          colKey: "op",
          title: "操作",
          align: "center",
          width: 120,
          fixed: 'right'
        },
      ],
      dataLoading: false,
      projectCategoryOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: '',
        changeType: '',
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showPageSize: true,
        pageSizeOptions: [10, 20, 30, 50],
        showFirstAndLastPageBtn: false,
        onChange: (pageInfo) => {
          Object.assign(this.pagination,pageInfo)
          this.queryParams.pageNum = pageInfo.current || 1;
          this.queryParams.pageSize = pageInfo.pageSize;
          this.getList()
        },
      },
    }
  },
  created(){
    this.getList();
    this.getDeclareTree();
  },
  methods:{
    getDeclareTree() {
      this.$api.kjxm.project.planCategoryList().then(response => {
        this.projectCategoryOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    sortChange(sort){
      this.sort = sort;
      let orderByColumn = []
      let isAsc = []
      if(sort instanceof Array){
        orderByColumn = sort.map(val=>val.sortBy)
        isAsc = sort.map(val=>val.descending?`desc`:`asc`)
      }else {
        orderByColumn = [sort.sortBy]
        isAsc = [sort.descending?`desc`:`asc`]
      }
      this.queryParams.orderByColumn = orderByColumn.join(",")
      this.queryParams.isAsc = isAsc.join(",")
      this.getList();
    },
    createPDF(row){
      const instance = this.$loading({
        fullscreen: true,
        attach: 'body',
        preventScrollThrough: false,
      });
      this.$api.kjxm.implement.changeApplyPDF(row.id).then(response => {
        window.open(response.data.fullFilePath, '_blank')
        instance.hide();
      }).catch((e) => {
        instance.hide();
        this.$message.error(e.toString());
      });
    },
    update(row, type){
      const taskId = row.id;
      sessionStorage.setItem(`${taskId}-changeApply-objId`, row.id);
      sessionStorage.removeItem(`${taskId}-changeApply-editOpen`);
      if(type===2){
        // 设置不可编辑
        sessionStorage.setItem(`${taskId}-changeApply-editOpen`, '0');
      }
      this.$router.push({
        path: `/kjxm/other/implement/change-apply/${taskId}`,
        query: {title: `${row.contract.projectName}-变更申请`}
      });
    },
    toApply(){
      this.$router.push({
        path: `/kjxm/other/implement/change-apply/${Date.parse(new Date())}`,
      })
    },
    getList(){
      this.dataLoading = true;
      this.$api.kjxm.implement.changeApplyMyList(this.queryParams).then(response => {
        this.pagination.total = response.total;
        this.data = response.rows;
        this.dataLoading = false;
      }).catch((e) => {
        this.dataLoading = false;
        this.$message.error(e.toString());
      });
    },
    delObj(row){
      const confirmDia = this.$dialog.confirm({
        header: "系统提示",
        body: `是否确认删除当前数据项？`,
        theme: "warning",
        onConfirm: ({ e }) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          })
          this.$api.kjxm.implement.changeApplyDel(row.id).then(
            (res) => {
              this.getList();
              this.$message.success("删除成功");
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            confirmDia.update({
              confirmBtn: {
                loading: false,
              },
            })
            this.$message.error(e.toString());
          });
        }
      });
    }
  }
}
</script>

<style scoped>

</style>
